package com.haircut.sys.service.login.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.haircut.sys.constant.CacheConstants;
import com.haircut.sys.model.user.SysUser;
import com.haircut.sys.service.dept.IDeptService;
import com.haircut.sys.service.login.ILoginService;
import com.haircut.sys.service.login.TokenService;
import com.haircut.sys.service.role.IRoleService;
import com.haircut.sys.service.user.IUserService;
import com.haircut.sys.utils.user.SecurityUtils;
import com.haircut.sys.vo.dept.DeptDetailVo;
import com.haircut.sys.vo.role.RoleVo;
import com.haircut.sys.vo.user.LoginReqVo;
import com.haircut.sys.vo.user.LoginUserVo;
import com.haircut.sys.vo.user.UserVo;
import com.modular.constant.BaseCodeDesc;
import com.modular.enums.DataStts;
import com.modular.exception.ModularException;
import com.modular.security.JwtTokenService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private JwtTokenService jwtTokenService;
    /**
     * 登录
     * @param reqVo
     * @return
     */
    @Override
    public LoginUserVo login(LoginReqVo reqVo)
    {
        validateCaptcha(reqVo.getCode(),reqVo.getIidd());
        SysUser sysUser =  userService.findByAccount(reqVo.getUserAcount());
        if(!sysUser.getUserwd().equals(SecureUtil.md5(reqVo.getUserPwd()))){
            throw new ModularException(BaseCodeDesc.DEFATUL_MSG,"用户名称和密码错误");
        }
        if(ObjectUtil.notEqual(sysUser.getDataStts(), DataStts.ENABLED.getCode())){
            throw new ModularException(BaseCodeDesc.DEFATUL_MSG,"用户不是启用状态，不能登录");
        }
        DeptDetailVo detailVo = deptService.findDetail(sysUser.getDeptId());

        LoginUserVo userVo = new LoginUserVo();
        BeanUtils.copyProperties(sysUser,userVo);
        RoleVo roleVo =  roleService.findDetail(userVo.getRoleId());
        userVo.setDataScope(roleVo.getDataScope());
        userVo.setUserId(sysUser.getId());
        userVo.setUserAccount(sysUser.getUserAccount());
        userVo.setRealName(sysUser.getRealName());
        userVo.setRoleName(roleVo.getRoleName());
        userVo.setDeptName(detailVo.getDeptName());
        userVo.setLoginTime(System.currentTimeMillis());
        if(reqVo.isHasAuthorities()) {
            userVo.setAuthorities(roleService.findLoginPermissionList(roleVo.getId()));
        }
        tokenService.saveToken(userVo);
        return userVo;
    }

    /**
     * 获得当前用户信息
     * @return
     */
    @Override
    public LoginUserVo getInfo()
    {
        return SecurityUtils.getLoginUser();
    }

    /**
     * 登出
     */
    @Override
    public void logout()
    {
        jwtTokenService.logout(this.getInfo().getToken());
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String code, String uuid)
    {

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisTemplate.opsForValue().get(verifyKey);
//        redisTemplate.delete(verifyKey);
        if (!code.equalsIgnoreCase(captcha))
        {
           throw new ModularException(BaseCodeDesc.DEFATUL_MSG,"验证码错误");
        }

    }

    /**
     * 查询当前登录的用户信息
     * @return
     */
    @Override
    public UserVo getUserProfile()
    {
        String userId = SecurityUtils.getUserId();
        UserVo sysUser =  userService.findDetail(userId);
        DeptDetailVo detailVo = deptService.findDetail(sysUser.getDeptId());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser,userVo);
        RoleVo roleVo =  roleService.findDetail(userVo.getRoleId());
        sysUser.setRoleName(roleVo.getRoleName());
        sysUser.setDeptName(detailVo.getDeptName());
        return sysUser;
    }



}
